package org.yinxue.swing.core.domain;

import org.yinxue.swing.core.util.FileUtil;

import java.io.File;

public class FileObject {
    public String name;
    public File file;

    public FileObject() {
    }

    public FileObject(String name, File file) {
        this.name = name;
        this.file = file;
    }

    public String getText() {
        if (file == null) {
            return "null";
        }
        return FileUtil.readText(file);
    }

    public void write(String text) {
        FileUtil.writeText(file, text);
    }

    @Override
    public String toString() {
        return name;
    }


    public void delete() {
        // TODO 循环删除子文件然后删除目录
        FileUtil.deleteAllFile(file);

    }

    public FileObject newFile(String fileName) {
        File newFile = FileUtil.newFile(file, fileName);
        return new FileObject(fileName, newFile);
    }

    public FileObject newDir(String dirName) {
        File newDir = FileUtil.newDir(file, dirName);
        return new FileObject(dirName, newDir);
    }

    public boolean isDir() {
        return file.isDirectory();
    }

    // 查找子模块的路径，然后用于拼接运行代码
    public String findModule(String projectText) {
        File nowFile = this.file;
        for (; ; ) {
            File parent = nowFile.getParentFile();
            if (parent == null) {
                return null;
            }
            if (parent.getAbsolutePath().equals(projectText)) {
                return nowFile.getName();
            }
            nowFile = parent;
        }
    }

    public String findPackage() {
        String text = getText();
        String[] lines = text.split("\n");
        for (String line : lines) {
            if (line.startsWith("package ")) {
                // java package 格式
                if (line.indexOf(";") != -1) {
                    return line.substring(line.indexOf("package ") + 8, line.lastIndexOf(";"));
                    // groovy 可以省略 ;
                } else {
                    return line.substring(line.indexOf("package ") + 8);
                }
            }
        }
        return null;
    }

    public boolean isJvmLang() {
        return file.getName().endsWith(".java") || file.getName().endsWith(".groovy");
    }

    public boolean isGroovy() {
        return file.getName().endsWith(".groovy");
    }
}
